import React, {
    Component
} from 'react';
import {
    TextInput,
    StyleSheet,
    Text,
    View,
    Dimensions,
    ScrollView,
    TouchableOpacity,
    Image,
    Alert,
    ToastAndroid,
    ImageBackground
} from 'react-native';
import Util from './utils'

export default class MyANswearForType1 extends Component {
    constructor(props) {
        super(props);
        this.state = {
            selectId:'',
            userAnswer:[],
            ip:this.props.ip,
            count:0,
            inputValue:true,
            oldId:this.props.qainfo.id,
            intervalIndex:"",
            submitflag:false
        }
    }
    //**********用户答案*****开始 */
    _renderAnswerItem(item,index){
        return  (
            <View style={[styles.useransweritem]}>
                <TextInput
                style={{height: 50,width:200,fontSize:28,color:'#003365',fontWeight:'bold'}}
                placeholder=""
                underlineColorAndroid="transparent"
                onChangeText={(text) => this.setUserAnser(text,index)}
                // key={Math.random()}
                //  value={this.state.inputValue}
                />
            </View>
    );
    }
    setUserAnser(text,index){
        console.log(this.state.inputValue)
        let data = this.state.userAnswer
        data[index]=text
        this.setState({
            userAnswer:data,
            // inputValue:text
        })
    }
    _renderAnswer(){
        let list = []
        console.log(this.state.count)
        for(let i=0;i<this.state.count;i++){
            list.push(i)
        }
       // var list=new Array(3)

        if(list){
            return list.map( (item,index) => this._renderAnswerItem(item,index) );

        }
    }
    //**********用户答案*****结束 */
    //*******开始***********答案选项********** */
    _renderSelectAnswerItem (item){
        return (
        <TouchableOpacity onPress={()=>this.onPressItem(item)}>
            <View style={[styles.answeritem]}>
                <Text style={[styles.fontFormarrt]}>{item.answerOption}</Text>
            </View>
        </TouchableOpacity>
    )};
    _renderSelectAnswer(list){
        if(list){
            return list.map( item => this._renderSelectAnswerItem(item) );
        }
    }
    //*****结束*************答案选项 */
    onPressItem(item){
        let data = this.state.userAnswer
        if(data.length<this.state.count){
            data.push(item.answerOption)
            this.setState({
                userAnswer:data
            })
        }

    }
    componentDidMount(){
        let intervalIndex = setInterval(()=>this.getData()
        ,1000)
        let count =0
        this.props.qainfo.options.map((obj)=>{
            console.log(obj)
            if(obj.isRight=="1"){
                count++
            }
        })
        this.setState({
            count:count,
            intervalIndex:intervalIndex
        })
    }
    componentWillUnmount(){
        clearInterval(this.state.intervalIndex);
    }
    saveinfo() {
        if(this.state.submitflag){
            ToastAndroid.show('您已经回答过该题,不可重复回答', ToastAndroid.SHORT);
        }else{
        const {navigate} = this.props.navigation

        Alert.alert(
            '确认提交',
            '提交后就不能修改答案了，确定提交您的答案吗？',
            [
              {text: '提交', onPress: () => {
                    //if(this.props.qainfo.startAnswer=="1"){
                        let url = `http://${this.state.ip}:10081/api/submitAnswer` //人力
                        let data = this.props.qainfo
                        data.userCode = this.props.userCode
                        data.userName = this.props.userName
                        data.answer = this.state.userAnswer.join(Util.joinSplit)
                        data.timeOfAnswer = (new Date()).getTime()
                        Util.post(url, data, (result) => {
                            if(result.status==301){
                                ToastAndroid.show('您已经回答过该题,不可重复回答', ToastAndroid.SHORT);
                            }else if(result.status==200){
                                this.setState({
                                    inputValue:false
                                })
                                ToastAndroid.show('提交成功', ToastAndroid.SHORT);
                            }else{
                                ToastAndroid.show('提交失败', ToastAndroid.SHORT);
                            }
                        }, (error) => {
                            ToastAndroid.show('提交失败', ToastAndroid.SHORT);

                        })
              }},
              {text: '取消', onPress: () => console.log('Cancel Pressed'), style: 'cancel'},
            ],
            { cancelable: false }
          )
        }
    }
    getData(){
        const {navigate} = this.props.navigation
        let url = `http://${this.props.ip}:10081/api/getQuestionForApp?userCode=${this.props.userCode}`//人力
        let that =this
        this.setState({
            inputValue:true
        })
        Util.get(url, (result) => {

            if(result.status==301){
             //   ToastAndroid.show('您的账号已在其他地方登录,不可以重复使用', ToastAndroid.LONG);
//                navigate("LoginScreen")
                that.setState({
                    submitflag:true
                })
            }else{

                if(this.state.oldId!=result.id){
                    console.log("this.props.qainfo.id!=result.id",this.props.qainfo.id!=result.id,this.props.qainfo.id,result.id)
                    let count =0
                    result.options.map((obj)=>{
                        console.log(obj)
                        if(obj.isRight=="1"){
                            count++
                        }
                    })
                    that.setState({
                        count:count,
                        oldId:result.id,
                        inputValue:false
                    })
                    console.table(this.state.beixuanxiang)
                }else{
                    // that.setState({
                       
                    //     inputValue:true
                    // })
                }
             
            }
        },(error)=>{

        })
    }
    render() {
        return (
            <View>
                <View style={[styles.main,{width:Dimensions.get('window').width,height:Dimensions.get('window').height}]} >
                    <ImageBackground source={require('./image/kuang.png')} style={{width:Dimensions.get('window').width*80/100,height:400}} resizeMode='stretch'>
                        <View style={[styles.conteont]}>
                            <ScrollView>
                                <Text style={[styles.fontColor]}>
                                    {this.props.qainfo.stem}
                                </Text> 
                            </ScrollView>
                        </View>
                    </ImageBackground>
                    <View style={[styles.answerYes]}>
                    <Image source={require('./image/left.png')} style={[styles.imgStyle]}></Image>

                    <ScrollView horizontal>

                        {/* {this.state.inputValue?:null} */}
                        {this._renderAnswer()}
                        </ScrollView>
                        <Image source={require('./image/right.png')} style={[styles.imgStyle]}></Image>

                    </View>
                    {this.props.qainfo.startAnswer=="1"?
                        <View style={[styles.viewClass]}>
                            <TouchableOpacity onPress={this.saveinfo.bind(this)}>
                                <View style={[styles.btnClass]} >
                                    <Text style={{color:'#003365',fontSize:40}}>提  交</Text>
                                </View>
                            </TouchableOpacity>
                        </View>
                        :null
                    }
                </View>
            </View>
        )
    }
}
const styles = StyleSheet.create({
    main:{
        paddingLeft:40,
        paddingRight:40,
         alignItems:'center',
         marginTop:50
    },
    fontColor:{
        color:'#000000',
        fontSize: 22,
        fontFamily: 'Georgia',
        // fontWeight: 'bold',

    },
    conteont:{
        height:290,
        //backgroundColor: '#d00000',
        width:670,
        marginTop:70,
        marginLeft:70,
        padding:20
    },
    answerlist2:{
        width:750,
        marginRight:100,
        padding:20,
        flexDirection: 'row',
        flexWrap: 'wrap',
        //backgroundColor:'#ff0'
    },
    userfontFormarrt:{
        color: '#003365',
        fontSize:28,
        fontWeight:'bold'
    },
    useransweritem:{
         justifyContent: 'center',
         alignItems:'center',
        borderColor: '#003365',
        borderWidth:1 ,
        // padding: 10,
        width: 200,
        marginLeft:20,
        marginRight:20,
        borderRadius: 5,
        height:69
    },
    answerYes:{
        height:100,
        width:600,
        flexDirection: 'row',
        flexWrap: 'wrap',  
        marginRight:200,
        marginTop:60,
        //backgroundColor:'#d00000',
        flexDirection: 'row',
        flexWrap: 'wrap',
    },
    btnClass:{
        width:120,
        height:70,
         justifyContent:'center',
         alignItems:'center',
         marginTop:50,
         marginRight:5,
         borderRadius: 5,
         borderColor:'#003365' ,
         borderWidth: 3,
         color:'#003365' ,
     },
     viewClass:{
         width:125,
         justifyContent:'flex-end',
         alignItems:'flex-end',
         paddingLeft:40,
         paddingRight:0,
         position:'absolute',
         bottom:110,
         right:100,
         zIndex:999
     },
     imgStyle:{
        width:50,
        height:50,
        // backgroundColor:'#d00'
        opacity:0.3,
        marginTop:10
     }
})